<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: general.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined('_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' );

function clear_string($value) {
	$string = str_replace("'", '', $value);
	$string = str_replace(')', '', $string);
	$string = str_replace('(', '', $string);
	$array = explode(',', $string);
	return $array;
}

function check_stock($products_id) {
	global $db;

	unset($stock_flag);
	$stock_values = $db->db_query("SELECT
										products_quantity
									FROM
										".TABLE_PRODUCTS."
									WHERE
										products_id = '".$products_id."'");

	if($stock_values->fields['products_quantity'] <= '0') {
		$stock_flag = 'true';
		$stock_warn = TEXT_WARN_MAIN;

		$attribute_stock_values = $db->db_query("SELECT
													attributes_stock,
													options_values_id
												FROM
													".TABLE_PRODUCTS_ATTRIBUTES."
												WHERE
													products_id = '".$products_id."'");

		while(!$attribute_stock_values->EOF) {
			if($attribute_stock_values->fields['attributes_stock'] <= '0') {
				$stock_flag = 'true';
				$which_attribute = $db->db_query("SELECT
														products_options_values_name
													FROM
														".TABLE_PRODUCTS_OPTIONS_VALUES."
													WHERE
														products_options_values_id = '".$attribute_stock_values->fields['options_values_id']."'
													AND
														language_id = '".$_SESSION['languages_id']."'");

				$stock_warn .= ', '.$which_attribute->fields['products_options_values_name'];
			}
			$attribute_stock_values->MoveNext();
		}
	}
	if($stock_flag == 'true' && $products_id != '')
		return '<div class="stock_warn">'.$stock_warn.'</div>';
	else
		return image(DIR_WS_IMAGES.'icon_status_green.gif', $stock_values->fields['products_quantity'].' '.IMAGE_ICON_STATUS_GREEN_STOCK);
}

// Set Categorie Status
function set_categories_status($categories_id, $status) {
	global $db;

	if ($status == '1')
		return $db->db_query("UPDATE ".TABLE_CATEGORIES." set categories_status = '1' WHERE categories_id = '".$categories_id."'");

	elseif ($status == '0')
		return $db->db_query("UPDATE ".TABLE_CATEGORIES." set categories_status = '0' WHERE categories_id = '".$categories_id."'");

	else
		return -1;
}

function set_groups($categories_id, $permission_array) {
	global $db;

	$products = $db->db_query("SELECT
									products_id
								FROM
									".TABLE_PRODUCTS_TO_CATEGORIES."
								WHERE
									categories_id = '".$categories_id."'");
	while(!$products->EOF) {
		$db->db_perform(TABLE_PRODUCTS, $permission_array, 'update', 'products_id = '.$db->db_prepare($products->fields['products_id']));
		$products->MoveNext();
	}

	$db->db_perform(TABLE_CATEGORIES, $permission_array, 'update', 'categories_id = '.$db->db_prepare($categories_id));

	$categories = $db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id='".$categories_id."'");
	while(!$categories->EOF) {
		set_groups($categories->fields['categories_id'], $permission_array);
		$categories->MoveNext();
	}
}

function check_permission($pagename) {
	global $db;
	
	$access_permission = $db->db_query("SELECT 
											g_".$_SESSION['customers_status']['customers_admin_id']." 
										FROM 
											".TABLE_ADMIN_ACCESS_RIGHTS." 
										WHERE 
											file_name = '".$pagename.(isset($_GET['gID'])?'-'.$_GET['gID']:'')."'");

	if($access_permission->fields['g_'.$_SESSION['customers_status']['customers_admin_id']] == 1 || $pagename == 'start' || $pagename == 'error' || $pagename == 'hold_session')
		return true;
	else
		return false;
}

function redirect($url) {
	global $logger;
	if(isset($_POST['menu'])) {
		if(strstr($url, '?'))
			header('Location: '.$url.'&menu='.$_POST['menu']);
		else
			header('Location: '.$url.'?menu='.$_POST['menu']);
	} else
		header('Location: '.$url);
	
	if(STORE_PAGE_PARSE_TIME == 'true') {
		if(!is_object($logger))
			$logger = new logger;
		$logger->timer_stop();
	}
	exit;
}

function customers_name($customers_id) {
	global $db;

	$customers = $db->db_query("SELECT 
									customers_firstname, 
									customers_lastname 
								FROM 
									".TABLE_CUSTOMERS." 
								WHERE 
									customers_id = '".$customers_id."'");
	return $customers->fields['customers_firstname'].' '.$customers->fields['customers_lastname'];
}

function get_path($current_category_id = '') {
	global $cPath_array, $db;

	if ($current_category_id == '')
		$cPath_new = implode('_', $cPath_array);

	else {
		if (sizeof($cPath_array) == 0)
			$cPath_new = $current_category_id;

		else {
			$cPath_new = '';
			$last_category_ = $db->db_query("SELECT parent_id FROM ".TABLE_CATEGORIES." WHERE categories_id = '".$cPath_array[(sizeof($cPath_array) - 1)]."'");

			$current_category = $db->db_query("SELECT parent_id FROM ".TABLE_CATEGORIES." WHERE categories_id = '".$current_category_id."'");

			if ($last_category->fields['parent_id'] == $current_category->fields['parent_id']) {
				for ($i = 0, $n = sizeof($cPath_array) - 1; $i < $n; $i ++) {
					$cPath_new .= '_'.$cPath_array[$i];
				}
			} else {
				for ($i = 0, $n = sizeof($cPath_array); $i < $n; $i ++) {
					$cPath_new .= '_'.$cPath_array[$i];
				}
			}
			$cPath_new .= '_'.$current_category_id;
			if (substr($cPath_new, 0, 1) == '_') {
				$cPath_new = substr($cPath_new, 1);
			}
		}
	}

	return 'cPath='.$cPath_new;
}

function get_all_get_params($exclude_array = '') {

	if ($exclude_array == '')
		$exclude_array = array();

	$get_url = '';

	reset($_GET);
	while (list ($key, $value) = each($_GET)) {
		if (($key != session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)))
			$get_url .= $key.'='.$value.'&';
	}

	return $get_url;
}

function date_long($raw_date) {
	if (($raw_date == '0000-00-00 00:00:00') || ($raw_date == ''))
		return false;

	$year = (int) substr($raw_date, 0, 4);
	$month = (int) substr($raw_date, 5, 2);
	$day = (int) substr($raw_date, 8, 2);
	$hour = (int) substr($raw_date, 11, 2);
	$minute = (int) substr($raw_date, 14, 2);
	$second = (int) substr($raw_date, 17, 2);

	return strftime(DATE_FORMAT_LONG, mktime($hour, $minute, $second, $month, $day, $year));
}

function date_short($raw_date) {
	if (($raw_date == '0000-00-00 00:00:00') || ($raw_date == ''))
		return false;

	$year = substr($raw_date, 0, 4);
	$month = (int) substr($raw_date, 5, 2);
	$day = (int) substr($raw_date, 8, 2);
	$hour = (int) substr($raw_date, 11, 2);
	$minute = (int) substr($raw_date, 14, 2);
	$second = (int) substr($raw_date, 17, 2);

	if(@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year)
		return date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
	else
		return preg_replace('/2037'.'$/', $year, date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, 2037)));
}

function datetime_short($raw_datetime, $format = DATE_TIME_FORMAT) {
	if (($raw_datetime == '0000-00-00 00:00:00') || ($raw_datetime == ''))
		return false;

	$year = (int) substr($raw_datetime, 0, 4);
	$month = (int) substr($raw_datetime, 5, 2);
	$day = (int) substr($raw_datetime, 8, 2);
	$hour = (int) substr($raw_datetime, 11, 2);
	$minute = (int) substr($raw_datetime, 14, 2);
	$second = (int) substr($raw_datetime, 17, 2);

	return strftime($format, mktime($hour, $minute, $second, $month, $day, $year));
}

function get_category_tree($parent_id = '0', $spacing = '', $exclude = '', $category_tree_array = '', $include_itself = false) {
	global $db;

	if(!is_array($category_tree_array))
		$category_tree_array = array();
	if((sizeof($category_tree_array) < 1) && ($exclude != '0'))
		$category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);

	if($include_itself) {
		$category = $db->db_query("SELECT
										cd.categories_name
									FROM
										".TABLE_CATEGORIES_DESCRIPTION." cd
									WHERE
										cd.language_id = '".$_SESSION['languages_id']."'
									AND
										cd.categories_id = '".$parent_id."'");

		$category_tree_array[] = array('id' => $parent_id, 'text' => $category->fields['categories_name']);
	}

	$categories = $db->db_query("SELECT
										c.categories_id,
										cd.categories_name,
										c.parent_id
									FROM
										".TABLE_CATEGORIES." c, ".TABLE_CATEGORIES_DESCRIPTION." cd
									WHERE
										c.categories_id = cd.categories_id
									AND
										cd.language_id = '".$_SESSION['languages_id']."'
									AND
										c.parent_id = '".$parent_id."'
									ORDER BY
										c.sort_order, cd.categories_name");

	while(!$categories->EOF) {
		if ($exclude != $categories->fields['categories_id']) {
			$category_tree_array[] = array(	'id' => $categories->fields['categories_id'],
											'text' => $spacing.$categories->fields['categories_name']);
		}
		$category_tree_array = get_category_tree($categories->fields['categories_id'], $spacing.'&nbsp;&nbsp;&nbsp;', $exclude, $category_tree_array);
		$categories->MoveNext();
	}

	return $category_tree_array;
}

function draw_products_pull_down($name, $parameters = '', $exclude = '') {
	global $currencies, $db, $price;
	
	if ($exclude == '')
		$exclude = array();

	$select_string = '<select name="'.$name.'"';
	if ($parameters)
		$select_string .= ' '.$parameters;

	$select_string .= '>';
	$products = $db->db_query("SELECT
									p.products_id,
									p.products_model,
									pd.products_name,
									p.products_tax_class_id,
									p.products_price
								FROM
									".TABLE_PRODUCTS." p,
									".TABLE_PRODUCTS_DESCRIPTION." pd
								WHERE
									p.products_id = pd.products_id
								AND
									pd.language_id = '".$_SESSION['languages_id']."'
								ORDER BY
									products_name");

	while(!$products->EOF) {
		if (!in_array($products->fields['products_id'], $exclude)) {
			if (PRICE_IS_BRUTTO == 'true')
				$p_price = $price->format($products->fields['products_price'] * ((100 + get_tax_rate($products->fields['products_tax_class_id'])) / 100), true);
			else
				$p_price = $price->format($products->fields['products_price'], true);
				
			$select_string .= '<option value="'.$products->fields['products_id'].'">'.(!empty($products->fields['products_model']) ? $products->fields['products_model'].' - ': '').$products->fields['products_name'].' ('.$p_price.')</option>';
		}
		$products->MoveNext();
	}
	$select_string .= '</select>';

	return $select_string;
}

function cfg_pull_down_css_bg_pic_sets() {
	if ($dir = opendir(DIR_FS_CATALOG.'images/css_button_bg/')) {
		$pictures_array = array(array('id' => '', 'text' => TEXT_NONE));
		while (($pictures = readdir($dir)) !== false) {
			if(($pictures != ".") && ($pictures != ".."))
				$pictures_array[] = array('id' => $pictures, 'text' => $pictures);
		}
		closedir($dir);
		sort($pictures_array);
		return draw_pull_down_menu('configuration_value', $pictures_array, CSS_BUTTON_BACKGROUND_PIC);
	}
}

function cfg_pull_down_css_bg_pic_hover_sets() {
	if ($dir = opendir(DIR_FS_CATALOG.'images/css_button_bg/')) {
		$pictures_array = array(array('id' => '', 'text' => TEXT_NONE));
		while (($pictures = readdir($dir)) !== false) {
			if(($pictures != ".") && ($pictures != ".."))
				$pictures_array[] = array('id' => $pictures, 'text' => $pictures);
		}
		closedir($dir);
		sort($pictures_array);
		return draw_pull_down_menu('configuration_value', $pictures_array, CSS_BUTTON_BACKGROUND_PIC_HOVER);
	}
}

function options_name($options_id) {
	global $db;

	$options = $db->db_query("SELECT
									products_options_name
								FROM
									".TABLE_PRODUCTS_OPTIONS."
								WHERE
									products_options_id = '".$options_id."'
								AND
									language_id = '".$_SESSION['languages_id']."'");

	return $options->fields['products_options_name'];
}

function values_name($values_id) {
	global $db;

	$values = $db->db_query("SELECT
									products_options_values_name
								FROM
									".TABLE_PRODUCTS_OPTIONS_VALUES."
								WHERE
									products_options_values_id = '".$values_id."'
								AND
									language_id = '".$_SESSION['languages_id']."'");

	return $values->fields['products_options_values_name'];
}

function info_image($image, $alt, $width = '', $height = '') {
	if (($image) && (file_exists(DIR_FS_CATALOG_IMAGES.$image))) {
		$image = image(DIR_WS_CATALOG_IMAGES.$image, $alt, $width, $height);
	} else {
		$image = TEXT_IMAGE_NONEXISTENT;
	}

	return $image;
}

function info_image_c($image, $alt, $width = '', $height = '') {
	if(($image) && (file_exists(DIR_FS_CATALOG_IMAGES.'categories/'.$image))) {
		$size = getimagesize(DIR_FS_CATALOG_IMAGES.'categories/'.$image);
		if($size[0] < 200)
			$width = $size[0];
		$image = image(DIR_WS_CATALOG_IMAGES.'categories/'.$image, $alt, $width, $height);
	} else
		$image = TEXT_IMAGE_NONEXISTENT;

	return $image;
}

function product_thumb_image($image, $alt, $width = '', $height = '') {
	if(($image) && (file_exists(DIR_FS_CATALOG_THUMBNAIL_IMAGES.$image)))
		$image = image(DIR_WS_CATALOG_THUMBNAIL_IMAGES.$image, $alt, $width, $height);
	else
		$image = TEXT_IMAGE_NONEXISTENT;

	return $image;
}

function break_string($string, $len, $break_char = '-') {
	$l = 0;
	$output = '';
	for ($i = 0; $i < strlen($string); $i ++) {
		$char = substr($string, $i, 1);
		if ($char != ' ') {
			$l ++;
		} else {
			$l = 0;
		}
		if ($l > $len) {
			$l = 1;
			$output .= $break_char;
		}
		$output .= $char;
	}

	return $output;
}

function get_country_name($country_id) {
	global $db;

	$country = $db->db_query("SELECT countries_name FROM ".TABLE_COUNTRIES." WHERE countries_id = '".$country_id."'");

	if($country->_numOfRows <= 0)
		return $country_id;
	else
		return $country->fields['countries_name'];
}

function get_zone_name($country_id, $zone_id, $default_zone) {
	global $db;

	$zone = $db->db_query("SELECT zone_name FROM ".TABLE_ZONES." WHERE zone_country_id = '".$country_id."' AND zone_id = '".$zone_id."'");
	if($zone->_numOfRows > 0)
		return $zone->fields['zone_name'];
	else
		return $default_zone;
}

function browser_detect($component) {
	return stristr($_SERVER['HTTP_USER_AGENT'], $component);
}

function tax_classes_pull_down($parameters, $SELECTed = '') {
	global $db;

	$select_string = '<select '.$parameters.'>';
	$classes = $db->db_query("SELECT tax_class_id, tax_class_title FROM ".TABLE_TAX_CLASS." ORDER BY tax_class_title");

	while(!$classes->EOF) {
		$select_string .= '<option value="'.$classes->fields['tax_class_id'].'"';
		if ($SELECTed == $classes->fields['tax_class_id'])
			$select_string .= ' selected';
		$select_string .= '>'.$classes->fields['tax_class_title'].'</option>';
		$classes->MoveNext();
	}

	$select_string .= '</select>';

	return $select_string;
}

function geo_zones_pull_down($parameters, $SELECTed = '') {
	global $db;

	$select_string = '<select '.$parameters.'>';
	$zones = $db->db_query("SELECT geo_zone_id, geo_zone_name FROM ".TABLE_GEO_ZONES." ORDER BY geo_zone_name");

	while(!$zones->EOF) {
		$select_string .= '<option value="'.$zones->fields['geo_zone_id'].'"';
		if ($SELECTed == $zones->fields['geo_zone_id'])
			$select_string .= ' selected';
		$select_string .= '>'.$zones->fields['geo_zone_name'].'</option>';
		$zones->MoveNext();
	}
	$select_string .= '</select>';

	return $select_string;
}

function get_geo_zone_name($geo_zone_id) {
	global $db;

	$zones = $db->db_query("SELECT geo_zone_name FROM ".TABLE_GEO_ZONES." WHERE geo_zone_id = '".$geo_zone_id."'");

	if($zones->_numOfRows <= 0)
		$geo_zone_name = $geo_zone_id;
	else
		$geo_zone_name = $zones->fields['geo_zone_name'];

	return $geo_zone_name;
}

function address_format($address_format_id, $address, $html, $boln, $eoln) {
	global $db;

	$address_format = $db->db_query("SELECT address_format as format FROM ".TABLE_ADDRESS_FORMAT." WHERE address_format_id = '".$address_format_id."'");

	$company = addslashes($address['company']);
	$firstname = addslashes($address['firstname']);
	$cid = addslashes($address['csID']);
	$lastname = addslashes($address['lastname']);
	$street = addslashes($address['street_address']);
	$suburb = addslashes($address['suburb']);
	$city = addslashes($address['city']);
	$state = addslashes($address['state']);
	$country_id = $address['country_id'];
	$zone_id = $address['zone_id'];
	$postcode = addslashes($address['postcode']);
	$zip = $postcode;
	$country = get_country_name($country_id);
	$state = get_zone_code($country_id, $zone_id, $state);

	if($html) {
		// HTML Mode
		$HR = '<hr />';
		$hr = '<hr />';
		if(($boln == '') && ($eoln == "\n")) {
			$CR = '<br />';
			$cr = '<br />';
			$eoln = $cr;
		} else {
			$CR = $eoln.$boln;
			$cr = $CR;
		}

	} else {
		// Text Mode
		$CR = $eoln;
		$cr = $CR;
		$HR = '----------------------------------------';
		$hr = '----------------------------------------';
	}

	$statecomma = '';
	$streets = $street;
	if ($suburb != '')
		$streets = $street.$cr.$suburb;
	if ($firstname == '')
		$firstname = addslashes($address['name']);
	if ($country == '')
		$country = addslashes($address['country']);
	if ($state != '')
		$statecomma = $state.', ';

	$fmt = $address_format->fields['format'];
	eval ("\$address = \"$fmt\";");
	$address = stripslashes($address);

	if($company !='')
		$address = $company.$cr.$address;

	return $address;
}

function get_zone_code($country, $zone, $def_state) {
	global $db;

	$state_prov = $db->db_query("SELECT zone_code FROM ".TABLE_ZONES." WHERE zone_country_id = '".$country."' AND zone_id = '".$zone."'");

	if($state_prov->_numOfRows <= 0)
		$state_prov_code = $def_state;
	else
		$state_prov_code = $state_prov_values->fields['zone_code'];

	return $state_prov_code;
}

function get_uprid($prid, $params) {
	$uprid = $prid;
	if ((is_array($params)) && (!strstr($prid, '{'))) {
		while (list ($option, $value) = each($params))
			$uprid = $uprid.'{'.$option.'}'.$value;
	}

	return $uprid;
}

function get_prid($uprid) {
	$pieces = explode('{', $uprid);

	return $pieces[0];
}

function get_languages() {
	global $db;

	$languages = $db->db_query("SELECT
									languages_id,
									name,
									code,
									image,
									directory,
									status,
									status_admin
								FROM
									".TABLE_LANGUAGES."
								WHERE
									status_admin = 1
								ORDER BY
									sort_order");
	while(!$languages->EOF) {
		$languages_array[] = array(	'id' => $languages->fields['languages_id'],
									'name' => $languages->fields['name'],
									'code' => $languages->fields['code'],
									'image' => $languages->fields['image'],
									'directory' => $languages->fields['directory'],
									'status' => $languages->fields['status'],
									'status_admin' => $languages->fields['status_admin']);
		$languages->MoveNext();
	}
	return $languages_array;
}

function get_categories_name($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_name
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_name'];
}

function get_categories_url_alias($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_url_alias
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_url_alias'];
}

function get_categories_heading_title($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_heading_title
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_heading_title'];
}

function get_categories_description($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_description
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_description'];
}

function get_categories_description_2($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_description_2
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_description_2'];
}

function get_categories_pic_alt($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_pic_alt
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_pic_alt'];
}

function get_categories_meta_title($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_meta_title
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_meta_title'];
}

function get_categories_meta_description($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT
									categories_meta_description
								FROM
									".TABLE_CATEGORIES_DESCRIPTION."
								WHERE
									categories_id = ".$db->db_prepare($category_id)."
								AND
									language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_meta_description'];
}

function get_categories_box() {
	global $db;
	
	$boxes = $db->db_query("SELECT b.num, bn.box_title FROM ".TABLE_BOXES_NAMES." bn, ".TABLE_BOXES." b WHERE b.num > 0 AND bn.box_name = b.box_name AND bn.language_id = '".(int)$_SESSION['languages_id']."' ");
	while(!$boxes->EOF) {
		$box_array[] = array('id' => $boxes->fields['num'], 'text' => $boxes->fields['box_title']);
		$boxes->MoveNext();
	}
	return $box_array;
}

function get_categories_meta_keywords($category_id, $language_id) {
	global $db;

	$category = $db->db_query("SELECT categories_meta_keywords FROM ".TABLE_CATEGORIES_DESCRIPTION." WHERE categories_id = ".$db->db_prepare($category_id)." AND language_id = ".$db->db_prepare($language_id));

	return $category->fields['categories_meta_keywords'];
}

function get_categories_treepodia($category_id, $nr, $language_id) {
	global $db;

	$treepodia = $db->db_query("SELECT treepodia_".$nr." FROM ".TABLE_CATEGORIES_DESCRIPTION." WHERE categories_id = ".$db->db_prepare($category_id)." AND language_id = ".$db->db_prepare($language_id));
	return '<input name="treepodia_'.$nr.'_'.$language_id.'" value="'.$treepodia->fields['treepodia_'.$nr].'" type="text" style="width:80%" />';
}

function get_orders_status_name($orders_status_id, $language_id = '') {
	global $db;

	if (!$language_id)
		$language_id = $_SESSION['languages_id'];
	$orders_status = $db->db_query("SELECT orders_status_name FROM ".TABLE_ORDERS_STATUS." WHERE orders_status_id = '".$orders_status_id."' AND language_id = ".$db->db_prepare($language_id));

	return $orders_status->fields['orders_status_name'];
}

function get_cross_sell_name($cross_sell_group, $language_id = '') {
	global $db;

	if (!$language_id)
		$language_id = $_SESSION['languages_id'];
	$cross_sell = $db->db_query("SELECT groupname FROM ".TABLE_PRODUCTS_XSELL_GROUPS." WHERE products_xsell_grp_name_id = '".$cross_sell_group."' AND language_id = ".$db->db_prepare($language_id));

	return $cross_sell->fields['groupname'];
}

function get_shipping_status_name($shipping_status_id, $language_id = '') {
	global $db;

	if (!$language_id)
		$language_id = $_SESSION['languages_id'];
	$shipping_status = $db->db_query("SELECT shipping_status_name FROM ".TABLE_SHIPPING_STATUS." WHERE shipping_status_id = '".$shipping_status_id."' AND language_id = ".$db->db_prepare($language_id));

	return $shipping_status->fields['shipping_status_name'];
}

function get_orders_status() {
	global $db;

	$orders_status_array = array();
	$orders_status = $db->db_query("SELECT orders_status_id, orders_status_name FROM ".TABLE_ORDERS_STATUS." WHERE language_id = '".$_SESSION['languages_id']."' ORDER BY orders_status_id");
	while(!$orders_status->EOF) {
		$orders_status_array[] = array('id' => $orders_status->fields['orders_status_id'], 'text' => $orders_status->fields['orders_status_name']);
		$orders_status->MoveNext();
	}

	return $orders_status_array;
}

function get_cross_sell_groups() {
	global $db;

	$cross_sell_array = array();
	$cross_sell = $db->db_query("SELECT products_xsell_grp_name_id, groupname FROM ".TABLE_PRODUCTS_XSELL_GROUPS." WHERE language_id = '".$_SESSION['languages_id']."' ORDER BY products_xsell_grp_name_id");
	while(!$cross_sell->EOF) {
		$cross_sell_array[] = array('id' => $cross_sell->fields['products_xsell_grp_name_id'], 'text' => $cross_sell->fields['groupname']);
		$cross_sell->MoveNext();
	}
	return $cross_sell_array;
}

function get_products_vpe_name($products_vpe_id, $language_id = '') {
	global $db;

	if (!$language_id)
		$language_id = $_SESSION['languages_id'];
	$products_vpe = $db->db_query("SELECT products_vpe_name FROM ".TABLE_PRODUCTS_VPE." WHERE products_vpe_id = '".$products_vpe_id."' AND language_id = ".$db->db_prepare($language_id));

	return $products_vpe->fields['products_vpe_name'];
}

function get_shipping_status() {
	global $db;

	$shipping_status_array = array();
	$shipping_status = $db->db_query("SELECT shipping_status_id, shipping_status_name FROM ".TABLE_SHIPPING_STATUS." WHERE language_id = '".$_SESSION['languages_id']."' ORDER BY shipping_status_id");
	while(!$shipping_status->EOF) {
		$shipping_status_array[] = array('id' => $shipping_status->fields['shipping_status_id'], 'text' => $shipping_status->fields['shipping_status_name']);
		$shipping_status->MoveNext();
	}
	return $shipping_status_array;
}

function get_products_name($product_id, $language_id = 0) {
	global $db;

	if ($language_id == 0)
		$language_id = $_SESSION['languages_id'];
	$product = $db->db_query("SELECT products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_name'];
}

function get_products_url_alias($product_id, $language_id = 0) {
	global $db;

	if ($language_id == 0)
		$language_id = $_SESSION['languages_id'];
	$product = $db->db_query("SELECT products_url_alias FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_url_alias'];
}

function get_products_description($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_description FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_description'];
}

function get_products_treepodia($product_id, $nr, $language_id) {
	global $db;

	$treepodia = $db->db_query("SELECT treepodia_".$nr." FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));
	return '<input name="treepodia_'.$nr.'_'.$language_id.'" value="'.$treepodia->fields['treepodia_'.$nr].'" type="text" style="width:80%" />';
}

function get_products_short_description($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_short_description FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_short_description'];
}

function get_products_keywords($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_keywords FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_keywords'];
}

function get_products_meta_title($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_meta_title FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_meta_title'];
}

function get_products_meta_description($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_meta_description FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_meta_description'];
}

function get_products_meta_keywords($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_meta_keywords FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_meta_keywords'];
}

function get_products_tag_cloud($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_tag_cloud FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_tag_cloud'];
}

function get_products_url($product_id, $language_id) {
	global $db;

	$product = $db->db_query("SELECT products_url FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = '".$product_id."' AND language_id = ".$db->db_prepare($language_id));

	return $product->fields['products_url'];
}

function get_products_special_price($product_id, $customer_id, $qty = 1){
	global $db;

	$customer_group = $db->db_query("SELECT customers_status FROM ".TABLE_CUSTOMERS." WHERE customers_id = '".$customer_id."'");

	$personal = $db->db_query("SELECT personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$customer_group->fields['customers_status']." WHERE products_id=".(int)$product_id." AND quantity <= ".(int)$qty." ORDER BY quantity DESC LIMIT 1");
	if($personal->_numOfRows > 0)
		return $personal->fields['personal_offer'];

	$product = $db->db_query("SELECT specials_price_".$customer_group->fields['customers_status']." FROM ".TABLE_SPECIALS." WHERE products_id = '".(int)$product_id."' AND status");
	return $product->fields['specials_price_'.$customer_group->fields['customers_status']];
}

function get_brand_url($brand_id, $language_id) {
	global $db;

	$brand = $db->db_query("SELECT brand_url FROM ".TABLE_BRAND_INFO." WHERE brand_id = '".$brand_id."' AND languages_id = ".$db->db_prepare($language_id));

	return $brand->fields['brand_url'];
}

function get_countries($default = '') {
	global $db;

	$countries_array = array();
	if($default)
		$countries_array[] = array('id' => STORE_COUNTRY, 'text' => $default);

	$countries = $db->db_query("SELECT countries_id, countries_name FROM ".TABLE_COUNTRIES." ORDER BY countries_name");
	while(!$countries->EOF) {
		$countries_array[] = array('id' => $countries->fields['countries_id'], 'text' => $countries->fields['countries_name']);
		$countries->MoveNext();
	}

	return $countries_array;
}

function get_country_zones($country_id) {
	global $db;

	$zones_array = array();
	$zones = $db->db_query("SELECT zone_id, zone_name FROM ".TABLE_ZONES." WHERE zone_country_id = '".$country_id."' ORDER BY zone_name");
	while(!$zones->EOF) {
		$zones_array[] = array('id' => $zones->fields['zone_id'], 'text' => $zones->fields['zone_name']);
		$zones->MoveNext();
	}

	return $zones_array;
}

function prepare_country_zones_pull_down($country_id = '') {
	$pre = '';
	if ((!browser_detect('MSIE')) && (browser_detect('Mozilla/4'))) {
		for ($i = 0; $i < 45; $i ++)
			$pre .= '&nbsp;';
	}

	$zones = get_country_zones($country_id);

	if (sizeof($zones) > 0) {
		$zones_SELECT = array(array ('id' => '', 'text' => PLEASE_SELECT));
		$zones = array_merge($zones_SELECT, $zones);
	} else {
		$zones = array(array ('id' => '', 'text' => TYPE_BELOW));
		if ((!browser_detect('MSIE')) && (browser_detect('Mozilla/4'))) {
			for ($i = 0; $i < 9; $i ++) {
				$zones[] = array('id' => '', 'text' => $pre);
			}
		}
	}

	return $zones;
}

function get_address_formats() {
	global $db;

	$address_format = $db->db_query("SELECT address_format_id FROM ".TABLE_ADDRESS_FORMAT." ORDER BY address_format_id");
	$address_format_array = array();
	while(!$address_format->EOF) {
		$address_format_array[] = array('id' => $address_format->fields['address_format_id'], 'text' => $address_format->fields['address_format_id']);
		$address_format->MoveNext();
	}
	return $address_format_array;
}

function cfg_pull_down_country_list($country_id) {
	return draw_pull_down_menu('configuration_value', get_countries(), $country_id);
}

function cfg_pull_down_zone_list($zone_id) {
	return draw_pull_down_menu('configuration_value', get_country_zones(STORE_COUNTRY), $zone_id);
}

function cfg_pull_down_tax_classes($tax_class_id, $key = '') {
	global $db;

	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');

	$tax_class_array = array(array ('id' => '0', 'text' => TEXT_NONE));
	$tax_class = $db->db_query("SELECT tax_class_id, tax_class_title FROM ".TABLE_TAX_CLASS." ORDER BY tax_class_title");
	while(!$tax_class->EOF) {
		$tax_class_array[] = array('id' => $tax_class->fields['tax_class_id'], 'text' => $tax_class->fields['tax_class_title']);
		$tax_class->MoveNext();
	}

	return draw_pull_down_menu($name, $tax_class_array, $tax_class_id);
}

function cfg_textarea($text) {
	return draw_textarea_field('configuration_value', false, 35, 5, $text,'class="resizable"');
}

function cfg_get_zone_name($zone_id) {
	global $db;

	$zone = $db->db_query("SELECT zone_name FROM ".TABLE_ZONES." WHERE zone_id = '".$zone_id."'");

	if($zone->_numOfRows <= 0)
		return $zone_id;
	else
		return $zone->fields['zone_name'];
}

function set_banner_status($banners_id, $status) {
	global $db;

	if($status == '1')
		return $db->db_query("UPDATE ".TABLE_BANNERS." set status = '1', expires_impressions = NULL, expires_date = NULL, date_status_change = NULL WHERE banners_id = '".$banners_id."'");
	elseif ($status == '0')
		return $db->db_query("UPDATE ".TABLE_BANNERS." set status = '0', date_status_change = now() WHERE banners_id = '".$banners_id."'");
	else
		return -1;
}

function set_specials_status($specials_id, $status) {
	global $db;

	if($status == '1')
		return $db->db_query("UPDATE ".TABLE_SPECIALS." set status = '1', expires_date = NULL, date_status_change = NULL WHERE specials_id = '".$specials_id."'");

	elseif ($status == '0')
		return $db->db_query("UPDATE ".TABLE_SPECIALS." set status = '0', date_status_change = now() WHERE specials_id = '".$specials_id."'");
	else
		return -1;
}

function cfg_select_option($select_array, $key_value, $key = '') {
	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');
	$clean_name = strtolower((($key) ? $key : 'configuration_value'));
	$string = '<div id="'.$clean_name.'" class="dn">';
	for ($i = 0, $n = sizeof($select_array); $i < $n; $i++) {
		$string .= '<input class="css_radio '.$clean_name.'" id="'.$clean_name.$i.'" type="radio" name="'.$name.'" value="'.$select_array[$i].'"';
		if ($key_value == $select_array[$i])
			$string .= ' checked="cecked"';
		$string .= '><label'; 
		if(strtolower($select_array[$i]) == 'true' OR strtolower($select_array[$i]) == 'false' OR strtolower($select_array[$i]) == 'True' OR strtolower($select_array[$i]) == 'False')
			$string .= ' class="'.(($select_array[$i] == 'true' OR $select_array[$i] == 'True') ? 'ui-green-button' : 'ui-red-button').'"';
		$string .= ' for="'.$clean_name.$i.'">'.niceValue($select_array[$i]).'</label>';
	}
	$string .= '</div><script type="text/javascript">$(function(){$("#'.$clean_name.'").buttonset().fadeIn();})</script>';
	return $string;
}

function mod_select_option($select_array, $key_name, $key_value) {
	reset($select_array);
	while (list ($key, $value) = each($select_array)) { $i++;
		if (is_int($key))
			$key = $value;
		$string .= '<input type="radio" id="'.strtolower($key_name).'_'.$i.'" name="configuration['.$key_name.']" value="'.$key.'"';
		if ($key_value == $key)
			$string .= ' checked="cecked"';
		$string .= '> <label for="'.strtolower($key_name).$i.'">'.$value.'</label>';
	}
	return $string;
}

function get_system_information() {
	global $db;

	$data = $db->db_query("SELECT now() AS datetime");

	list ($system, $host, $kernel) = preg_split('/[\s,]+/', @exec('uname -a'), 5);

	return array(	'date' => datetime_short(date('Y-m-d H:i:s')),
					'system' => $system,
					'kernel' => $kernel,
					'host' => $host,
					'ip' => gethostbyname($host),
					'uptime' => @exec('uptime'),
					'http_server' => $_SERVER['SERVER_SOFTWARE'],
					'php' => PHP_VERSION,
					'zend' => (function_exists('zend_version') ? zend_version() : ''),
					'db_server' => DB_SERVER,
					'db_ip' => gethostbyname(DB_SERVER),
					'db_version' => 'MySQL '. (function_exists('mysql_get_server_info') ? mysql_get_server_info() : ''),
					'db_date' => datetime_short($data->fields['datetime']));
}

function generate_category_path($id, $from = 'category', $categories_array = '', $index = 0) {
	global $db;

	if(!is_array($categories_array))
		$categories_array = array();

	if($from == 'product') {
		$categories = $db->db_query("SELECT categories_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE products_id = '".$id."'");
		while(!$categories->EOF) {
			if($categories->fields['categories_id'] == '0')
				$categories_array[$index][] = array('id' => '0', 'text' => TEXT_TOP);
			else {
				$category = $db->db_query("SELECT
												cd.categories_name,
												c.parent_id
											FROM
												".TABLE_CATEGORIES." c,
												".TABLE_CATEGORIES_DESCRIPTION." cd
											WHERE
												c.categories_id = '".$categories->fields['categories_id']."'
											AND
												c.categories_id = cd.categories_id
											AND
												cd.language_id = '".$_SESSION['languages_id']."'");

				$categories_array[$index][] = array('id' => $categories->fields['categories_id'], 'text' => $category->fields['categories_name']);
				if(not_null($category->fields['parent_id']) && $category->fields['parent_id'] != '0')
					$categories_array = generate_category_path($category->fields['parent_id'], 'category', $categories_array, $index);

				$categories_array[$index] = array_reverse($categories_array[$index]);
			}
			$index ++;
			$categories->MoveNext();
		}

	} elseif ($from == 'category') {
		$category = $db->db_query("SELECT
										cd.categories_name,
										c.parent_id
									FROM
										".TABLE_CATEGORIES." c,
										".TABLE_CATEGORIES_DESCRIPTION." cd
									WHERE
										c.categories_id = '".$id."'
									AND
										c.categories_id = cd.categories_id
									AND
										cd.language_id = '".$_SESSION['languages_id']."'");
		$categories_array[$index][] = array('id' => $id, 'text' => $category->fields['categories_name']);
		if(not_null($category->fields['parent_id']) && $category->fields['parent_id'] != '0')
			$categories_array = generate_category_path($category->fields['parent_id'], 'category', $categories_array, $index);
	}

	return $categories_array;
}

function output_generated_category_path($id, $FROM = 'category') {
	$calculated_category_path_string = '';
	$calculated_category_path = generate_category_path($id, $FROM);
	for ($i = 0, $n = sizeof($calculated_category_path); $i < $n; $i ++) {
		for ($j = 0, $k = sizeof($calculated_category_path[$i]); $j < $k; $j ++) {
			$calculated_category_path_string .= $calculated_category_path[$i][$j]['text'].'&nbsp;&gt;&nbsp;';
		}
		$calculated_category_path_string = substr($calculated_category_path_string, 0, -16).'<br>';
	}
	$calculated_category_path_string = substr($calculated_category_path_string, 0, -4);

	if (strlen($calculated_category_path_string) < 1)
		$calculated_category_path_string = TEXT_TOP;

	return $calculated_category_path_string;
}

function del_image_file($image) {
	if(file_exists(DIR_FS_CATALOG_POPUP_IMAGES.$image))
		@unlink(DIR_FS_CATALOG_POPUP_IMAGES.$image);
	if(file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.$image))
		@unlink(DIR_FS_CATALOG_ORIGINAL_IMAGES.$image);
	if(file_exists(DIR_FS_CATALOG_THUMBNAIL_IMAGES.$image))
		@unlink(DIR_FS_CATALOG_THUMBNAIL_IMAGES.$image);
	if(file_exists(DIR_FS_CATALOG_INFO_IMAGES.$image))
		@unlink(DIR_FS_CATALOG_INFO_IMAGES.$image);
	if(file_exists(DIR_FS_CATALOG_ICON_IMAGES.$image))
		@unlink(DIR_FS_CATALOG_ICON_IMAGES.$image);
}

function del_movie_file($movie) {
	if(file_exists(DIR_WS_CATALOG_MOVIES.$movie))
		@unlink(DIR_WS_CATALOG_MOVIES.$movie);
}

function remove_order($order_id, $restock = false) {
	global $db;

	if($restock == 'on') {
		$order = $db->db_query("SELECT
									orders_products_id,
									products_id,
									products_quantity
								FROM
									".TABLE_ORDERS_PRODUCTS."
								WHERE
									orders_id = '".$order_id."'");

		while(!$order->EOF) {
			$db->db_query("UPDATE
								".TABLE_PRODUCTS."
							SET
								products_quantity = products_quantity + ".$order->fields['products_quantity'].",
								products_ordered = products_ordered - ".$order->fields['products_quantity']."
							WHERE
								products_id = '".$order->fields['products_id']."'");

			$result = $db->db_query("SELECT
											*
										FROM
											".TABLE_ORDERS_PRODUCTS_ATTRIBUTES."
										WHERE
											orders_id = '". $order_id."'
										AND
											orders_products_id = '".$order->fields['orders_products_id']."'");
			while(!$result->EOF) {
				$attributes_id = get_products_attributes_id($order->fields['products_id'],$row->fields['products_options'],$row->fields['products_options_values']);
				$db->db_query("UPDATE
									".TABLE_PRODUCTS_ATTRIBUTES."
								SET
									attributes_stock = attributes_stock + '".$order->fields['products_quantity']."'
								WHERE
									products_attributes_id = '".$attributes_id."'");
				$result->MoveNext();
			}
			$order->MoveNext();
		}
	}

	$db->db_query("DELETE FROM ".TABLE_ORDERS." WHERE orders_id = ".$db->db_prepare($order_id)."");
	$db->db_query("DELETE FROM ".TABLE_ORDERS_PRODUCTS." WHERE orders_id = ".$db->db_prepare($order_id)."");
	$db->db_query("DELETE FROM ".TABLE_ORDERS_PRODUCTS_ATTRIBUTES." WHERE orders_id = ".$db->db_prepare($order_id)."");
	$db->db_query("DELETE FROM ".TABLE_ORDERS_STATUS_HISTORY." WHERE orders_id = ".$db->db_prepare($order_id)."");
	$db->db_query("DELETE FROM ".TABLE_ORDERS_TOTAL." WHERE orders_id = ".$db->db_prepare($order_id)."");
}

function reset_cache_block($cache_block) {
	global $cache_blocks;

	for ($i = 0, $n = sizeof($cache_blocks); $i < $n; $i ++) {
		if ($cache_blocks[$i]['code'] == $cache_block) {
			if ($cache_blocks[$i]['multiple']) {
				if ($dir = @opendir(DIR_FS_CACHE)) {
					while ($cache_file = readdir($dir)) {
						$cached_file = $cache_blocks[$i]['file'];
						$languages = get_languages();
						for ($j = 0, $k = sizeof($languages); $j < $k; $j ++) {
							$cached_file_unlink = preg_replace('/-language/', '-'.$languages->fields[$j]['directory'], $cached_file);
							if (preg_match('/^'.$cached_file_unlink.'/', $cache_file)) {
								@ unlink(DIR_FS_CACHE.$cache_file);
							}
						}
					}
					closedir($dir);
				}
			} else {
				$cached_file = $cache_blocks[$i]['file'];
				$languages = get_languages();
				for ($i = 0, $n = sizeof($languages); $i < $n; $i ++) {
					$cached_file = preg_replace('/-language/', '-'.$languages->fields[$i]['directory'], $cached_file);
					@ unlink(DIR_FS_CACHE.$cached_file);
				}
			}
			break;
		}
	}
}

function get_file_permissions($mode) {
	// determine type
	if (($mode & 0xC000) == 0xC000) { // unix domain socket
		$type = 's';
	}
	elseif (($mode & 0x4000) == 0x4000) { // directory
		$type = 'd';
	}
	elseif (($mode & 0xA000) == 0xA000) { // symbolic link
		$type = 'l';
	}
	elseif (($mode & 0x8000) == 0x8000) { // regular file
		$type = '-';
	}
	elseif (($mode & 0x6000) == 0x6000) { //bBlock special file
		$type = 'b';
	}
	elseif (($mode & 0x2000) == 0x2000) { // character special file
		$type = 'c';
	}
	elseif (($mode & 0x1000) == 0x1000) { // named pipe
		$type = 'p';
	} else { // unknown
		$type = '?';
	}

	// determine permissions
	$owner['read'] = ($mode & 00400) ? 'r' : '-';
	$owner['write'] = ($mode & 00200) ? 'w' : '-';
	$owner['execute'] = ($mode & 00100) ? 'x' : '-';
	$group['read'] = ($mode & 00040) ? 'r' : '-';
	$group['write'] = ($mode & 00020) ? 'w' : '-';
	$group['execute'] = ($mode & 00010) ? 'x' : '-';
	$world['read'] = ($mode & 00004) ? 'r' : '-';
	$world['write'] = ($mode & 00002) ? 'w' : '-';
	$world['execute'] = ($mode & 00001) ? 'x' : '-';

	// adjust for SUID, SGID AND sticky bit
	if ($mode & 0x800)
		$owner['execute'] = ($owner['execute'] == 'x') ? 's' : 'S';
	if ($mode & 0x400)
		$group['execute'] = ($group['execute'] == 'x') ? 's' : 'S';
	if ($mode & 0x200)
		$world['execute'] = ($world['execute'] == 'x') ? 't' : 'T';

	return $type.$owner['read'].$owner['write'].$owner['execute'].$group['read'].$group['write'].$group['execute'].$world['read'].$world['write'].$world['execute'];
}

function remove($source) {
	global $message_stack, $remove_error;

	if (isset ($remove_error))
		$remove_error = false;

	if (is_dir($source)) {
		$dir = dir($source);
		while ($file = $dir->read()) {
			if (($file != '.') && ($file != '..')) {
				if (is_writeable($source.'/'.$file)) {
					remove($source.'/'.$file);
				} else {
					$message_stack->add(sprintf(ERROR_FILE_NOT_REMOVEABLE, $source.'/'.$file), 'error');
					$remove_error = true;
				}
			}
		}
		$dir->close();

		if (is_writeable($source)) {
			rmdir($source);
		} else {
			$message_stack->add(sprintf(ERROR_DIRECTORY_NOT_REMOVEABLE, $source), 'error');
			$remove_error = true;
		}
	} else {
		if (is_writeable($source)) {
			unlink($source);
		} else {
			$message_stack->add(sprintf(ERROR_FILE_NOT_REMOVEABLE, $source), 'error');
			$remove_error = true;
		}
	}
}

function display_tax_value($value, $padding = TAX_DECIMAL_PLACES) {
	if (strpos($value, '.')) {
		$loop = true;
		while ($loop) {
			if (substr($value, -1) == '0') {
				$value = substr($value, 0, -1);
			} else {
				$loop = false;
				if (substr($value, -1) == '.') {
					$value = substr($value, 0, -1);
				}
			}
		}
	}

	if ($padding > 0) {
		if ($decimal_pos = strpos($value, '.')) {
			$decimals = strlen(substr($value, ($decimal_pos +1)));
			for ($i = $decimals; $i < $padding; $i ++) {
				$value .= '0';
			}
		} else {
			$value .= '.';
			for ($i = 0; $i < $padding; $i ++) {
				$value .= '0';
			}
		}
	}

	return $value;
}

function get_tax_class_title($tax_class_id) {
	global $db;

	if($tax_class_id == '0')
		return TEXT_NONE;
	else {
		$classes = $db->db_query("SELECT tax_class_title FROM ".TABLE_TAX_CLASS." WHERE tax_class_id = '".$tax_class_id."'");
		return $classes->fields['tax_class_title'];
	}
}

function banner_image_extension() {
	if (function_exists('imagetypes')) {
		if (imagetypes() & IMG_PNG) {
			return 'png';
		}
		elseif (imagetypes() & IMG_JPG) {
			return 'jpg';
		}
		elseif (imagetypes() & IMG_GIF) {
			return 'gif';
		}
	}
	elseif (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
		return 'png';
	}
	elseif (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
		return 'jpg';
	}
	elseif (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
		return 'gif';
	}

	return false;
}
/*
function calculate_tax($price, $tax) {
	global $currencies;
	return round($price * $tax / 100, $currencies->currencies[DEFAULT_CURRENCY]['decimal_places']);
}
*/
function call_function($function, $parameter, $object = '') {
	if(function_exists(call_user_func)) {
		if ($object == '') {
			return @call_user_func($function, $parameter);
		} else {
			return @call_user_func(array($object, $function), $parameter);
		}
	}
}

function get_zone_class_title($zone_class_id) {
	global $db;

	if($zone_class_id == '0')
		return TEXT_NONE;
	else {
		$classes = $db->db_query("SELECT geo_zone_name FROM ".TABLE_GEO_ZONES." WHERE geo_zone_id = '".$zone_class_id."'");
		return $classes->fields['geo_zone_name'];
	}
}

function cfg_pull_down_template_sets() {
	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');
	if ($dir = opendir(DIR_FS_CATALOG.'templates/')) {
		while (($templates = readdir($dir)) !== false) {
			if (is_dir(DIR_FS_CATALOG.'templates/'."//".$templates) && ($templates != "CVS") && ($templates != ".") && ($templates != ".svn") && ($templates != "..") && $templates !='mobile')
				$templates_array[] = array('id' => $templates, 'text' => $templates);
		}
		closedir($dir);
		sort($templates_array);
		return draw_pull_down_menu($name, $templates_array, CURRENT_TEMPLATE);
	}
}

function cfg_pull_down_trusted_shop_template() {
	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');
	if ($dir = opendir(DIR_FS_CATALOG.'templates/'.CURRENT_TEMPLATE.'/boxes/trusted_shop/')) {
		while (($trusted_templates = readdir($dir)) !== false) {
			if (($trusted_templates != "CVS") && ($trusted_templates != ".") && ($trusted_templates != ".svn") && ($trusted_templates != "..")) {
				$trusted_templates_array[] = array('id' => $trusted_templates, 'text' => $trusted_templates);
			}
		}
		closedir($dir);
		sort($trusted_templates_array);
		return draw_pull_down_menu($name, $trusted_templates_array, TRUSTED_SHOP_TEMPLATE);
	}
}

function cfg_pull_down_zone_classes($zone_class_id, $key = '') {
	global $db;

	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');

	$zone_class_array = array(array ('id' => '0', 'text' => TEXT_NONE));
	$zone_class = $db->db_query("SELECT geo_zone_id, geo_zone_name FROM ".TABLE_GEO_ZONES." ORDER BY geo_zone_name");
	while(!$zone_class->EOF) {
		$zone_class_array[] = array('id' => $zone_class->fields['geo_zone_id'], 'text' => $zone_class->fields['geo_zone_name']);
		$zone_class->MoveNext();
	}

	return draw_pull_down_menu($name, $zone_class_array, $zone_class_id);
}

function cfg_pull_down_order_statuses($order_status_id, $key = '') {
	global $db;

	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');

	$statuses_array = array(array ('id' => '1', 'text' => TEXT_DEFAULT));
	$statuses = $db->db_query("SELECT orders_status_id, orders_status_name FROM ".TABLE_ORDERS_STATUS." WHERE language_id = '".$_SESSION['languages_id']."' ORDER BY orders_status_name");
	while(!$statuses->EOF) {
		$statuses_array[] = array('id' => $statuses->fields['orders_status_id'], 'text' => $statuses->fields['orders_status_name']);
		$statuses->MoveNext();
	}

	return draw_pull_down_menu($name, $statuses_array, $order_status_id);
}

function get_order_status_name($order_status_id, $language_id = '') {
	global $db;

	if ($order_status_id < 1)
		return TEXT_DEFAULT;

	if (!is_numeric($language_id))
		$language_id = $_SESSION['languages_id'];

	$status_query = $db->db_query("SELECT orders_status_name FROM ".TABLE_ORDERS_STATUS." WHERE orders_status_id = '".$order_status_id."' AND language_id = ".$db->db_prepare($language_id));

	return $status->fields['orders_status_name'];
}

function get_customers_statuses() {
	global $db;

	$customers_statuses_array = array(array ());
	$customers_statuses = $db->db_query("SELECT
												customers_status_id,
												customers_status_name,
												customers_status_image,
												customers_status_public,
												customers_status_discount,
												customers_status_ot_discount_flag,
												customers_status_ot_discount,
												customers_status_graduated_prices
											FROM
												".TABLE_CUSTOMERS_STATUS."
											WHERE
												language_id = '".$_SESSION['languages_id']."'
											ORDER BY
												customers_status_id");
	$i = 1;
	while(!$customers_statuses->EOF) {
		$i = $customers_statuses->fields['customers_status_id'];
		$customers_statuses_array[$i] = array(	'id' => $customers_statuses->fields['customers_status_id'],
												'text' => $customers_statuses->fields['customers_status_name'],
												'csa_public' => $customers_statuses->fields['customers_status_public'],
												'csa_image' => $customers_statuses->fields['customers_status_image'],
												'csa_discount' => $customers_statuses->fields['customers_status_discount'],
												'csa_ot_discount_flag' => $customers_statuses->fields['customers_status_ot_discount_flag'],
												'csa_ot_discount' => $customers_statuses->fields['customers_status_ot_discount'],
												'csa_graduated_prices' => $customers_statuses->fields['customers_status_graduated_prices']);
		$customers_statuses->MoveNext();
	}
	return $customers_statuses_array;
}

function get_customer_status($customers_id) {
	global $db;

	$customer_status_array = array();
	$customer_status = $db->db_query("SELECT
											customers_status,
											member_flag,
											customers_status_name,
											customers_status_public,
											customers_status_image,
											customers_status_discount,
											customers_status_ot_discount_flag,
											customers_status_ot_discount,
											customers_status_graduated_prices
										FROM
											".TABLE_CUSTOMERS."
												LEFT JOIN
													".TABLE_CUSTOMERS_STATUS." ON customers_status = customers_status_id
										WHERE
											customers_id='".$customers_id."'
										AND
											language_id = '".$_SESSION['languages_id']."'");
	return $customer_status->fields;
}

function get_customers_status_name($customers_status_id, $language_id = '') {
	global $db;

	if(!$language_id)
		$language_id = $_SESSION['languages_id'];

	$customers_status = $db->db_query("SELECT customers_status_name FROM ".TABLE_CUSTOMERS_STATUS." WHERE customers_status_id = '".$customers_status_id."' AND language_id = ".$db->db_prepare($language_id));
	return $customers_status->fields['customers_status_name'];
}

function cfg_pull_down_customers_status_list($customers_status_id, $key = '') {
	$name = (($key) ? 'configuration['.$key.']' : 'configuration_value');
	return draw_pull_down_menu($name, get_customers_statuses(), $customers_status_id);
}

function get_user_info($customer_id) {
	global $db;

	$user_info = $db->db_query("SELECT customers_ip, customers_ip_date, customers_host, customers_advertiser, customers_referer_url FROM ".TABLE_CUSTOMERS_IP." WHERE customers_id = '".$customer_id."'");
	return $user_info->fields;
}

function get_uploaded_file($filename) {
	if(isset($_FILES[$filename])) {
		$uploaded_file = array('name' => $_FILES[$filename]['name'], 'type' => $_FILES[$filename]['type'], 'size' => $_FILES[$filename]['size'], 'tmp_name' => $_FILES[$filename]['tmp_name']);

	}else {
		$uploaded_file = array('name' => $GLOBALS[$filename.'_name'], 'type' => $GLOBALS[$filename.'_type'], 'size' => $GLOBALS[$filename.'_size'], 'tmp_name' => $GLOBALS[$filename]);
	}

	return $uploaded_file;
}

function get_group_price($group_id, $product_id) {
	global $db;

	$group_price = $db->db_query("SELECT personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$group_id." WHERE products_id = '".$product_id."' AND quantity=1");

	if($group_price->_numOfRows <= 0) {
		$db->db_query("INSERT INTO ".TABLE_PERSONAL_OFFERS_BY.$group_id." (price_id, products_id, quantity, personal_offer) VALUES ('', '".$product_id."', '1', '0.00')");
		$price = $db->db_query("SELECT personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$group_id." WHERE products_id = '".$product_id."' ORDER BY quantity ASC");
		$group_price->fields['personal_offer'] = $price->fields['personal_offer'];

	} else
		if($price->_numOfRows > 1) {
			while(!$group_price->EOF) {
				$group_price['personal_offer'] = $price->fields['personal_offer'];
				$group_price->MoveNext();
			}
			$db->db_query("DELETE FROM ".TABLE_PERSONAL_OFFERS_BY.$group_id." WHERE products_id='".$product_id."' AND quantity=1");
			$db->db_query("INSERT INTO ".TABLE_PERSONAL_OFFERS_BY.$group_id." (price_id, products_id, quantity, personal_offer) VALUES ('', '".$product_id."', '1', '".$group_price->fields['personal_offer']."')");
			$price = $db->db_query("SELECT personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$group_id." WHERE products_id = '".$product_id."' ORDER BY quantity ASC");
			$group_price->fields['personal_offer'] = $price->fields['personal_offer'];
		}

	return $group_price->fields['personal_offer'];
}

function format_price($price_string, $price_special, $currency, $allow_tax, $tax_rate = '') {
	global $db;

	$currencies = $db->db_query("SELECT
                                      symbol_left,
                                      symbol_right,
                                      decimal_places,
                                      value
                                  FROM
                                      ".TABLE_CURRENCIES."
                                  WHERE
                                      code = '".$currency."'");

	$currencies_data = array();
	$currencies_data = array(	'SYMBOL_LEFT' => $currencies->fields['symbol_left'],
								'SYMBOL_RIGHT' => $currencies->fields['symbol_right'],
								'DECIMAL_PLACES' => $currencies->fields['decimal_places'],
								'VALUE' => $currencies->fields['value']);

	if($allow_tax == 1)
		$price_string = $price_string / ((100 + $tax_rate) / 100);

	$price_string = number_format($price_string, $currencies_data['DECIMAL_PLACES'], '.', '');

	if($price_special == '1')
		$price_string = $currencies_data['SYMBOL_LEFT'].' '.$price_string.' '.$currencies_data['SYMBOL_RIGHT'];

	return $price_string;
}

function get_lang_definition($search_lang, $lang_array, $modifier) {
	$search_lang = $search_lang.$modifier;
	return $lang_array[$search_lang];
}

function CheckExt($filename, $ext) {
	$passed = FALSE;
	$testExt = "\.".$ext."$";
	if (preg_match('/'.$testExt.'/i', $filename)) {
		$passed = TRUE;
	}
	return $passed;
}

function get_status_users($status_id) {
	global $db;

	$status = $db->db_query("SELECT COUNT(customers_status) AS count FROM ".TABLE_CUSTOMERS." WHERE customers_status = '".$status_id."'");

	return $status->fields['count'];
}

function mkdirs($path, $perm) {

	if (is_dir($path))
		return true;

	else {
		if (!mkdir($path, $perm))
			return false;
		mkdir($path, $perm);
		return true;
	}
}

function spaceUsed($dir) {
	if (is_dir($dir)) {
		if ($dh = opendir($dir)) {
			while(($file = readdir($dh)) !== false) {
				if (is_dir($dir.$file) && $file != '.' && $file != '..')
					spaceUsed($dir.$file.'/');
				else
					$total += filesize($dir.$file);
			}
			closedir($dh);
		}
	}
	return $total;
}

function create_coupon_code($salt = "secret", $length = SECURITY_CODE_LENGTH) {
	global $db;

	$ccid = md5(uniqid("", "salt"));
	$ccid .= md5(uniqid("", "salt"));
	$ccid .= md5(uniqid("", "salt"));
	$ccid .= md5(uniqid("", "salt"));
	srand((double) microtime() * 1000000); // seed the random number generator
	$random_start = @ rand(0, (128 - $length));
	$good_result = 0;
	while ($good_result == 0) {
		$id1 = substr($ccid, $random_start, $length);
		$query = $db->db_query("SELECT coupon_code FROM ".TABLE_COUPONS." WHERE coupon_code = '".$id1."'");
		if($query->_numOfRows == 0)
			$good_result = 1;
	}
	return $id1;
}

function gv_account_update($customer_id, $gv_id) {
	global $db;

	$customer_gv = $db->db_query("SELECT amount FROM ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$customer_id."'");
	$coupon_gv = $db->db_query("SELECT coupon_amount FROM ".TABLE_COUPONS." WHERE coupon_id = '".$gv_id."'");

	if($customer_gv->_numOfRows > 0) {
		$new_gv_amount = $customer_gv->fields['amount'] + $coupon_gv->fields['coupon_amount'];
		$gv_query = $db->db_query("UPDATE ".TABLE_COUPON_GV_CUSTOMER." SET amount = '".$new_gv_amount."' WHERE customer_id = '".$customer_id."'");
	} else
		$gv_query = $db->db_query("INSERT INTO ".TABLE_COUPON_GV_CUSTOMER." (customer_id, amount) VALUES ('".$customer_id."', '".$coupon_gv->fields['coupon_amount']."')");
}

function draw_date_selector($prefix, $date = '') {
	$month_array = array();
	$month_array[1] = _JANUARY;
	$month_array[2] = _FEBRUARY;
	$month_array[3] = _MARCH;
	$month_array[4] = _APRIL;
	$month_array[5] = _MAY;
	$month_array[6] = _JUNE;
	$month_array[7] = _JULY;
	$month_array[8] = _AUGUST;
	$month_array[9] = _SEPTEMBER;
	$month_array[10] = _OCTOBER;
	$month_array[11] = _NOVEMBER;
	$month_array[12] = _DECEMBER;
	$usedate = getdate($date);
	$day = $usedate['mday'];
	$month = $usedate['mon'];
	$year = $usedate['year'];
	$date_selector = '<select name="'.$prefix.'_day">';
	for ($i = 1; $i < 32; $i ++) {
		$date_selector .= '<option value="'.$i.'"';
		if ($i == $day)
			$date_selector .= 'selected=""';
		$date_selector .= '>'.$i.'</option>';
	}
	$date_selector .= '</select>';
	$date_selector .= '<select name="'.$prefix.'_month">';
	for ($i = 1; $i < 13; $i ++) {
		$date_selector .= '<option value="'.$i.'"';
		if ($i == $month)
			$date_selector .= 'selected=""';
		$date_selector .= '>'.$month_array[$i].'</option>';
	}
	$date_selector .= '</select>';
	$date_selector .= '<select name="'.$prefix.'_year">';
	for ($i = 2011; $i < 2019; $i ++) {
		$date_selector .= '<option value="'.$i.'"';
		if ($i == $year)
			$date_selector .= 'selected=""';
		$date_selector .= '>'.$i.'</option>';
	}
	$date_selector .= '</select>';
	return $date_selector;
}

function getDownloads() {

	$files = array();

	$dir = DIR_FS_CATALOG.'download/';
	if ($fp = opendir($dir)) {
		while ($file = readdir($fp)) {
			if (is_file($dir.$file) && $file != '.htaccess') {
				$size = filesize($dir.$file);
				$files[] = array('id' => $file, 'text' => $file.' | '.format_filesize($size), 'size' => $size, 'date' => date("F d Y H:i:s.", filemtime($dir.$file)));
			}
		}
		closedir($fp);
	}
	return $files;
}

function try_upload($file = '', $destination = '', $permissions = '777', $extensions = '') {
	$file_object = new upload($file, $destination, $permissions, $extensions);
	if ($file_object->filename != '')
		return $file_object;
	else
		return false;
}

function button($value, $type='submit', $parameter='') {
   return '<button type="'.$type.'" class="button" onclick="this.blur();" '.$parameter.'>'.$value.'</button>';
}

function button_link($value, $href='javascript:void(0)', $parameter='') {
   return '<a href="'.$href.'" class="button" onclick="this.blur()" '.$parameter.' >'.$value.'</a>';
}

function contentTree($parent = 0, $active = '', $level = 1, $spacer = '&lfloor; ') {
	global $db;
	
	$content_data = $db->db_query("SELECT
										content_id,
										categories_id,
										parent_id,
										content_title,
										content_out_link,
										content_link_target,
										content_link_type,
										content_group
									FROM
										".TABLE_CONTENT_MANAGER."
									WHERE
										languages_id = '".(int)$_SESSION['languages_id']."'
									AND
										parent_id = '".$parent."'
									ORDER BY
										sort_order");
	if($content_data->_numOfRows) {
		if($level == 1)
			$content_string .= '<option value="0">Top</option>';
		while(!$content_data->EOF) {
			$content_string .= '<option'.($content_data->fields['content_group'] == $active ? ' selected=""' : '').' value="'.$content_data->fields['content_group'].'">'.($level > 1 ? $spacer : '').$content_data->fields['content_title'].'</option>';
			$content_string .= contentTree($content_data->fields['content_group'], $active, $level+1, '&nbsp;&nbsp;&nbsp;'.$spacer);
			$content_data->MoveNext();
		}
	}
	if($content_string)
		return $content_string;
}

function get_products_attributes_id($products_id, $products_options, $products_options_values) {
	global $db;

	$products_options_id = false;
	$products_options_values_id	= false;

	$result = $db->db_query("SELECT
								products_options_id
							FROM
								".TABLE_PRODUCTS_OPTIONS."
							WHERE
								products_options_name = '".$products_options."'
							AND
								language_id = '". $_SESSION['languages_id'] ."'");

	if($result->_numOfRows)
		$products_options_id = $result->fields['products_options_id'];

	$result = $db->db_query("SELECT
								pov.products_options_values_id AS products_options_values_id
							FROM
								".TABLE_PRODUCTS_OPTIONS_VALUES." pov,
								".TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS."	pov2po
							WHERE
								pov2po.products_options_id = '".$products_options_id."'
							AND
								pov2po.products_options_values_id = pov.products_options_values_id
							AND
								pov.products_options_values_name = '".$products_options_values."'
							AND
								pov.language_id	= '". $_SESSION['languages_id']."'");

	if($result->_numOfRows)
		$products_options_values_id = $result->fields['products_options_values_id'];

	if($products_options_id === false || $products_options_values_id === false)
		return false;

	$result = $db->db_query("SELECT
								products_attributes_id
							FROM
								".TABLE_PRODUCTS_ATTRIBUTES."
							WHERE
								products_id = '".$products_id."' AND
								options_id = '".$products_options_id."' AND
								options_values_id = '".$products_options_values_id."'");
	if($result->_numOfRows == 0)
		return false;

	return $result->fields['products_attributes_id'];
}

function wysiwyg($name, $value = '') {
	if(USE_WYSIWYG == 'true') {
		$j = '	<textarea id="'.$name.'" name="'.$name.'">'.$value.'</textarea>'."\n".
				'<script type="text/javascript" charset="utf-8">
					<!--
						var opts = {lang:\''.$_SESSION['language_code'].'\',
									styleWithCSS:true,
									cssfiles:[\''.DIR_WS_INCLUDES.'wysiwyg/css/textarea.css\'],
									height:250,
									toolbar:\'maxi\',
									fmOpen:function(callback){
										$(\'<div id="myelfinder" />\').elfinder({url:\''.DIR_WS_INCLUDES.'wysiwyg/connector.php\',
																				lang:\''.$_SESSION['language_code'].'\',
																				dialog:{width:700,
																						modal:true,
																						title:\'Dateimanager\'},
																				closeOnEditorCallback:true,
																				editorCallback:callback
																				});
									}};
						
						$(function() {
							setTimeout(function(){$(\'#'.$name.'\').elrte(opts);},800);
						});
					-->
				</script>';
	    return $j;
	}	
}

function check_size($size, $precision = '2', $status = ''){
	if(!empty($status)) {
		if($size >0)
			$style='style="color: #b20000;"';
		else
			$style = '';
	}
	if($size >= 1073741824)
		return '<span '.$style.'>' . round($size/pow(1024, 3), $precision) . ' GB</span>';
	elseif($size >= 1048576)
		return '<span '.$style.'>' . round($size/pow(1024, 2), $precision) . ' MB</span>';
	elseif($size >= 1024)
		return '<span '.$style.'>' . round($size/1024, $precision) . ' kB</span>';
	else
		return '<span '.$style.'>' . round($size, $precision) . ' Byte</span>';
}